package cn.lg.soar.common.util.current;

import java.util.HashMap;
import java.util.Map;

/**
 * 当前线程上下文
 * @author luguoxiang
 * @date 2022/3/29
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class CurrentThreadContext {

    private static final ThreadLocal<Map<String, Object>> MAP_THREAD_LOCAL = ThreadLocal.withInitial(() -> new HashMap<>(16));
    static ThreadLocal<String> RESOURCE_THREAD_LOCAL = ThreadLocal.withInitial(() -> "");

    /**
     * 获取当前资源
     * @return
     */
    public static String getResource() {
        return RESOURCE_THREAD_LOCAL.get();
    }

    /**
     * 设置当前资源
     * @return
     */
    public static void setResource(String resource) {
        RESOURCE_THREAD_LOCAL.set(resource);
    }

    /**
     * 加入数据
     * @param key
     * @param value
     */
    public static void put(String key, Object value) {
        MAP_THREAD_LOCAL.get().put(key, value);
    }

    /**
     * 获取数据
     * @param key
     * @return
     * @param <T>
     */
    public static Object get(String key) {
        return MAP_THREAD_LOCAL.get().get(key);
    }

    /**
     * 释放内存
     */
    public static void clear() {
        MAP_THREAD_LOCAL.remove();
        RESOURCE_THREAD_LOCAL.remove();
    }
}
